package com.zego.wawaji.ui.start;

import android.text.TextUtils;

import com.noble.library.basic.Constant;
import com.noble.library.basic.sp.PSP;
import com.zego.wawaji.base.module.ModuleMgr;
import com.noble.library.module.ModuleBase;
import com.noble.library.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.utils.BaseUtil;
import com.noble.library.basic.encrypt.EncryptUtil;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.third.ThirdConstant;
import com.zego.wawaji.third.auth.ThirdInfo;
import com.zego.wawaji.wawaji_client.AppTinkerLike;

import java.util.HashMap;

/**
 * 登录逻辑处理
 * Created by ZRP on 2016/9/19.
 */
public class LoginMgr implements ModuleBase {

    private final static String LOGINMGR_UID = "WAWAJI_UID";          // 保存当前登录用户账号信息 uid, pw
    private final static String LOGINMGR_AUTH = "WAWAJI_AUTH";        // 保存当前登录用户cookie, 不带auth=

    private final static String LOGINMGR_WX_OPENID = "WAWAJI_WX_OPENID"; // 保存微信用户openId

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    /**
     * 获取手机登录验证码
     */
    public void reqSendCode(String mobile, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("mobile", mobile);
        postParams.put("ver", ModuleMgr.getAppMgr().getVerCode());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqSendCode, postParams, complete);
    }

    /**
     * 手机号验证码验证
     */
    public void reqVerifyCode(String mobile, String code, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("mobile", mobile);
        postParams.put("code", code);
        postParams.put("os", "android");
        postParams.put("app_key", EncryptUtil.sha1(ModuleMgr.getAppMgr().getSignature()));
        postParams.put("pkgname", ModuleMgr.getAppMgr().getPackageName());
        postParams.put("imei", ModuleMgr.getAppMgr().getIMEI());
        postParams.put("is", ModuleMgr.getAppMgr().getIMSI());
        postParams.put("ver", ModuleMgr.getAppMgr().getVerCode());
        postParams.put("channel_id", ModuleMgr.getAppMgr().getChannel());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqVerifyCode, postParams, complete);
    }

    /**
     * 微信三方登录
     */
    public void weChatLogin(String openId, String unionid, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("open_id", openId);
        postParams.put("os", "android");
        postParams.put("app_key", EncryptUtil.sha1(ModuleMgr.getAppMgr().getSignature()));
        postParams.put("pkgname", ModuleMgr.getAppMgr().getPackageName());
        postParams.put("imei", ModuleMgr.getAppMgr().getIMEI());
        postParams.put("is", ModuleMgr.getAppMgr().getIMSI());
        postParams.put("ver", ModuleMgr.getAppMgr().getVerCode());
        postParams.put("union_id", unionid);
        postParams.put("channel_id", ModuleMgr.getAppMgr().getChannel());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.weChatLogin, postParams, complete);
    }

    /**
     * 测试登录：直接使用用户id登录软件
     */
    public void reqLoginTest(long uid, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("uid", uid);
        postParams.put("password", "54B0C58C7CE9F2A8B551351102EE0938");
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqLoginTest, postParams, complete);
    }

    /**
     * 保存微信登录OpenId
     */
    public void saveWXOpenId(String openid) {
        PSP.getInstance().put(LOGINMGR_WX_OPENID, openid);
    }

    /**
     * @return 获取用户微信openid
     */
    public String getWXOpenId() {
        return PSP.getInstance().getString(LOGINMGR_WX_OPENID, "");
    }

    private static ThirdInfo thirdInfo;  // 三方登录保存数据

    /**
     * 获取第三方的用户信息
     */
    public static ThirdInfo getThirdInfo() {
        if (thirdInfo == null) {
            thirdInfo = new ThirdInfo();
        }
        return thirdInfo;
    }

    public void setThirdInfo(ThirdInfo thirdInfo) {
        LoginMgr.thirdInfo = thirdInfo;
    }

    /**
     * 微信获取AccessToken
     */
    public void loadAccessToken(String code, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("appid", ThirdConstant.WEIXIN_APP_ID);
        getParams.put("secret", ThirdConstant.WEIXIN_APP_SECRET);
        getParams.put("code", code);
        getParams.put("grant_type", "authorization_code");
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXAccessToken, getParams, complete);
    }

    /**
     * 微信获取用户资料
     */
    public void loadUserInfo(String openid, String accessToken, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("access_token", accessToken);
        getParams.put("openid", openid);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXUserInfo, getParams, complete);
    }

    /**
     * 保存登录信息
     */
    public void putAllLoginInfo(long uid, boolean isUserLogin) {
        setUid(uid + "");
        setLoginInfo(uid, isUserLogin);  //设置登录状态
    }

    /**
     * 判断Cookie是否存在
     */
    public boolean checkAuthIsExist() {
        return !TextUtils.isEmpty(getCookie());
    }

    /**
     * 清空本地Cookie
     */
    public void clearCookie() {
        setCookie("");
    }

    /**
     * 保存cookie
     */
    public void setCookie(String cookie) {
        PSP.getInstance().put(LOGINMGR_AUTH, cookie);
    }

    /**
     * 获取cookie
     */
    public String getCookie() {
        String auth = PSP.getInstance().getString(LOGINMGR_AUTH, "");
        return TextUtils.isEmpty(auth) ? "" : "auth=" + auth;
    }

    /**
     * @return 获取无 auth= 的cookie
     */
    public String getAuth() {
        return PSP.getInstance().getString(LOGINMGR_AUTH, "");
    }


    /**
     * 获取cookie + vercode
     */
    public String getCookieVerCode() {
        String cookie = getCookie();
        if (!TextUtils.isEmpty(cookie)) {
            return cookie + ";" + "v=" + ModuleMgr.getAppMgr().getVerCode();
        } else {
            clearCookie();
            return "v=" + ModuleMgr.getAppMgr().getVerCode();
        }
    }


    // ========================  旧逻辑  后续删除======================================================
    // ************************************ 登录用户信息列表存储 *****************************


    /**
     * 设置登录信息，并发送登录信息。
     *
     * @param uid
     * @param isUserLogin 　进行登录请求或处于登录状态
     * @return
     */
    private boolean setLoginInfo(long uid, boolean isUserLogin) {
        AppTinkerLike.cookie = getCookie();
        changeIsLogin(isUserLogin && (TextUtils.isEmpty(AppTinkerLike.cookie) || uid == 0) ? 0 : uid);
        MsgMgr.getInstance().sendMsg(MsgType.MT_App_Login, AppTinkerLike.isLogin);
        return AppTinkerLike.isLogin;
    }

    private void changeIsLogin(long uid) {
        AppTinkerLike.uid = uid;
        AppTinkerLike.isLogin = uid != 0;
    }

    /**
     * 退出登录，并清空用户登录信息
     */
    public void logout() {
        setUid("");//清空uid
        clearCookie();//在setLoginInfo方法之前执行
        setLoginInfo(0, true);
    }

    public void exitLogin() {
        MsgMgr.getInstance().sendMsg(MsgType.MT_App_Login, false);
        logout();
        ModuleMgr.getCenterMgr().clearUserInfo();
    }

    /**
     * 保存单独的 uid
     *
     * @param uid
     */
    public void setUid(String uid) {
        PSP.getInstance().put(LOGINMGR_UID, uid);
    }

    public long getUid() {
        String uid = PSP.getInstance().getString(LOGINMGR_UID, "");
        if (!TextUtils.isEmpty(uid)) {
            return BaseUtil.getLong(uid, 0);
        }
        return 0L;
    }

    /**
     * 初始化登陆信息
     */
    public void initCookie() {
        long uid = getUid();
        if (uid == 0) {
            clearCookie();
            return;
        }
        setLoginInfo(uid, true);
    }

    /**
     * @return 程序是否是双击退出: 重新登录使用
     */
    public boolean isExitDouble() {
        return PSP.getInstance().getBoolean(Constant.APP_EXIT_DOUBLE, false);
    }

    public void updateExitDouble(boolean exit) {
        PSP.getInstance().put(Constant.APP_EXIT_DOUBLE, exit);
    }
}
